package com.hengxinguotong.zhihuichengjian.ui.statistics.attendance;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AttendanceCompanyDetailAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AttendanceCompanyRankingAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.CompanyAttendance;
import com.hengxinguotong.zhihuichengjian.bean.CompanyAttendanceListRes;
import com.hengxinguotong.zhihuichengjian.ui.statistics.OnActivityInteractionListener;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/3/28
 * <p>
 * 考勤报表-公司考勤排名
 */

public class AttendanceFormDataCompanyRankingFragment extends BaseFragment implements OnActivityInteractionListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.company_ranking_rv)
    RecyclerView companyRankingRv;
    @BindView(R.id.company_detail_rv)
    RecyclerView companyDetailRv;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.empty_img1)
    ImageView emptyImg1;
    @BindView(R.id.empty_img2)
    ImageView emptyImg2;
    Unbinder unbinder;

    private String startTime,//开始时间
            endTime;//	结束时间（月报表时，为空）
    private int pageIndex = 1;
    private int screenWidth;
    private List<CompanyAttendance> companyRankingList,
            companyDetailList;
    private AttendanceCompanyRankingAdapter companyRankingAdapter;
    private AttendanceCompanyDetailAdapter companyDetailAdapter;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.FORMDATA_RANKING:
                    companyRankingList = (List<CompanyAttendance>) msg.obj;
                    companyRankingAdapter.setDataList(companyRankingList);
                    showEmptyView1(companyRankingList.size() == 0);
                    break;
                case Constants.FORMDATA_DETAIL:
                    List<CompanyAttendance> datas = (List<CompanyAttendance>) msg.obj;
                    bindData(datas);
                    break;
            }
        }
    };

    public void setScreenWidth(int screenWidth) {
        this.screenWidth = screenWidth;
    }

    private void bindData(List<CompanyAttendance> datas) {
        if (pageIndex == 1) {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            companyDetailList = datas;
        } else {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            companyDetailList.addAll(datas);
        }
        showEmptyView2(companyDetailList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT) {
            refreshList.setPullUpEnable(true);
        } else {
            refreshList.setPullUpEnable(false);
        }
        companyDetailAdapter.setDataList(companyDetailList);
    }

    private void showEmptyView1(boolean isEmpty) {
        if (isEmpty) {
            emptyImg1.setVisibility(View.VISIBLE);
        } else {
            emptyImg1.setVisibility(View.GONE);
        }
    }

    private void showEmptyView2(boolean isEmpty) {
        if (isEmpty) {
            emptyImg2.setVisibility(View.VISIBLE);
        } else {
            emptyImg2.setVisibility(View.GONE);
        }
    }

    public AttendanceFormDataCompanyRankingFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param startTime Parameter .
     * @param endTime   Parameter .
     * @return A new instance of fragment AttendanceDataStatisticsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AttendanceFormDataCompanyRankingFragment newInstance(String startTime, String endTime) {
        AttendanceFormDataCompanyRankingFragment fragment = new AttendanceFormDataCompanyRankingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, startTime);
        args.putString(ARG_PARAM2, endTime);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            startTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_attendance_form_data_company_ranking, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);

        companyRankingList = new ArrayList<>();
        companyRankingAdapter = new AttendanceCompanyRankingAdapter(getActivity(), companyRankingList);
        companyRankingAdapter.setScreenWidth(screenWidth);
        companyRankingRv.setAdapter(companyRankingAdapter);
        companyRankingRv.setItemAnimator(new DefaultItemAnimator());
        companyRankingRv.setLayoutManager(getLayoutManager());

        companyDetailList = new ArrayList<>();
        companyDetailAdapter = new AttendanceCompanyDetailAdapter(getActivity(), companyDetailList);
        companyDetailRv.setAdapter(companyDetailAdapter);
        companyDetailRv.setItemAnimator(new DefaultItemAnimator());
        companyDetailRv.setLayoutManager(getLayoutManager());
    }

    /**
     * 主页面下拉刷新操作监听
     */
    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener() {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
            pageIndex = companyDetailList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private RecyclerView.LayoutManager getLayoutManager() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        return manager;
    }

    @Override
    public void onLazyLoad() {
        initData();
    }

    private void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getCompanyAttendanceRanking("搜索中…");
                getCompanyAttendanceDetail("搜索中…");
            }
        }, 500);
    }

    /**
     * 公司或班组考勤排名
     *
     * @param alert
     */
    public void getCompanyAttendanceRanking(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/attendanceReport/getCompanyOrTeamAttendanceRanking/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    CompanyAttendanceListRes res = gson.fromJson(json, CompanyAttendanceListRes.class);
                    if (res.getStatus() == 1) {
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_RANKING;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    } else {
                        showToast(res.getMsg());
                    }
                } else {
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 公司考勤明细
     *
     * @param alert
     */
    public void getCompanyAttendanceDetail(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
            jsonObject.put("pageNum", pageIndex);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/attendanceReport/getCompanyReport/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    CompanyAttendanceListRes res = gson.fromJson(json, CompanyAttendanceListRes.class);
                    if (res.getStatus() == 1) {
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_DETAIL;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    } else {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        showToast(res.getMsg());
                    }
                } else {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    @Override
    public void OnActivityInteraction(String startTime, String endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
